import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.DBConnection;

/**
 * This servlet is used to handle requests for removing pubs from the database.
 * 
 * @author Josef Hardi
 *
 */
public class RemovePub extends HttpServlet {
	
	/** Database connection **/
	private Connection conn = null;
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
    	throws ServletException,IOException {
		
		// Get the id pub
		int id = Integer.parseInt(request.getParameter("id"));
		
		conn = DBConnection.getConnection();
		
		PreparedStatement stmt = null;
		
		try {
			String query = "DELETE FROM Pub WHERE id = ?";
			stmt = conn.prepareStatement(query);
			
			stmt.setInt(1, id);
			
			int rowAffected = stmt.executeUpdate();
			
			// Throw the message
			request.setAttribute("dbmessage", rowAffected + " record removed!"); 
            RequestDispatcher rd=request.getRequestDispatcher("browse.jsp");  
            rd.forward(request, response);
		}
		catch (SQLException e) {
  	  		e.printStackTrace();
  	  	}
  	  	finally {
	    	try {
	            // Close everything.
	            if (stmt!= null) stmt.close();
	            if (conn!= null) conn.close();
	    	} 
	    	catch (Exception e) { // Trap all other exceptions
	    		e.printStackTrace();
	    	}
        }
	}
}
